package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exceptionhandler.DIYException;
import com.atguigu.servicebase.exceptionhandler.GlobalExceptionHandler;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
   //因为SubjectExcelListener不能交给spring管理，需要自己new，不能注入其他对象
    //不能实现数据库操作
    public EduSubjectService service;

    public SubjectExcelListener() {
    }

    public SubjectExcelListener(EduSubjectService service) {
        this.service = service;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
       if (subjectData==null){
        throw new DIYException(1,"文件数据位空！");
       }
       //一行一行读取，每次读取两个值，第一个位一级分类，第二个为二级分类
      //判断一级分类是否重复
     EduSubject oneSub = this.existOneSub(service, subjectData.getOneName());
       if (oneSub==null){
        //没有相同一级分类，进行添加
           oneSub = new EduSubject();
           oneSub.setParentId("0");
           oneSub.setTitle(subjectData.getOneName());
           service.save(oneSub);
       }
       //获取一级ID值
    String pid= oneSub.getId();
    //判断二级分类是否重复
        EduSubject twoSub = this.existTwoSub(service, subjectData.getTwoName(), pid);
        if (twoSub==null){
            //没有相同er级分类，进行添加
            twoSub = new EduSubject();
            twoSub.setParentId(pid);
            twoSub.setTitle(subjectData.getTwoName());
            service.save(twoSub);
        }


    }

    //判断一级分类不能重复添加
   private EduSubject existOneSub(EduSubjectService service,String name){
    QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
    wrapper.eq("title",name);
    wrapper.eq("parent_id",0);
    EduSubject one = service.getOne(wrapper);
    return one;
   }


    //判断二级分类不能重复添加
    private EduSubject existTwoSub(EduSubjectService service,String name,String pid){
     QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
     wrapper.eq("title",name);
     wrapper.eq("parent_id",pid);
     EduSubject two = service.getOne(wrapper);
     return two;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
